/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.travelFinder.controller;

import com.travelFinder.domain.Place;
import com.travelFinder.repository.PlaceRepository;
import com.travelFinder.service.DbServiceTemporary;
import com.travelFinder.service.JSONStructureBuilder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.neo4j.graphdb.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author szwl
 */
@Controller
public class RestController {

	@Autowired
	DbServiceTemporary dbService;
	@Autowired
	JSONStructureBuilder jsonBuilder;
	@Autowired
	PlaceRepository placeRepository;
	protected final static Logger logger = LoggerFactory.getLogger(RestController.class);

	@RequestMapping(value = "/rest/findConnections", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, Object> findConnections(final Model model, HttpServletRequest request, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if (request.getParameter("starting_point").equalsIgnoreCase(request.getParameter("destination"))) {
			Map<String, Object> root = new HashMap<String, Object>(2);

			root.put("connections", "");
			root.put("error", "Stacja końcowa i początkowa nie mogą być takie same.");
			return root;
		}
		Place start = placeRepository.findByPropertyValue("name", request.getParameter("starting_point"));
		Place end = placeRepository.findByPropertyValue("name", request.getParameter("destination"));



		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		Date d;
		try {
			d = df.parse(request.getParameter("starting_date"));
			logger.info(d.toString());
		} catch (Exception e) {
			Map<String, Object> root = new HashMap<String, Object>(2);

			root.put("connections", "");
			root.put("error", "" + request.getParameter("starting_date") + "  nie jest poprawną datą.");

			return root;
		}
		Map<String, Object> ret = jsonBuilder.validateArguments(start, end, d);
		if((Integer)ret.get("code") == 1 ){
			ret.remove("code");
			return ret;
		}

		Iterable<Path> paths = dbService.findShortestConnection(d, start, end, 2);

		return jsonBuilder.buildFromPaths(paths, d);

	}
}
